package com.example.dbsample.config.interceptor;

import cn.hutool.core.util.ArrayUtil;
import com.example.dbsample.util.datasource.DsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

//import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class DynamicDatasourceInterceptor implements HandlerInterceptor {
    private static final String HEADER_KEY_APP_ID = "businessLine";
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws IllegalArgumentException {
        String appId = this.determineDatasourceKey(request);
        DsUtils.setDsAndAppId(appId);
        return true;
    }

    // 1. header里传有效的appId，切换数据源；2.url里有appId标识
    private String determineDatasourceKey (HttpServletRequest request) {
        String appId = request.getHeader(HEADER_KEY_APP_ID);
        if(StringUtils.isBlank(appId)) {
            String[] requestUri = request.getRequestURI().split("/");
            //if(ArrayUtil.containsIgnoreCase(requestUri, AppIdEnum.CF.getAppId())) {
            if(ArrayUtil.containsIgnoreCase(requestUri, "sample2")) {
                //appId = AppIdEnum.CF.getAppId();
                appId = "sample2";
            }
        }
        //return StringUtils.isBlank(appId) ? AppIdEnum.sample1.getAppId() : appId;
        return StringUtils.isBlank(appId) ? "sample1" : appId;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
                                // @Nullable Exception ex) throws Exception {
        DsUtils.clearDsAndAppId();
    }
}
